
package com.eshore.ezone.utils;

import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

/**
 * 甯哥敤瀛楃涓叉嫾鎺ュ拰澶勭悊鍑芥暟
 * 
 * @author zhao xiaogang
 * @time 2012.3.13
 */
public class StringUtils {
    
    private static String buildSigInput(ArrayList<BasicNameValuePair> vpList) {
        final ArrayList<String> list = new ArrayList<String>();
        HashMap<String,String> param = new HashMap<String,String>();
        for (BasicNameValuePair vp : vpList) {
            param.put(vp.getName(), vp.getValue());
            list.add(vp.getName());
        }
        final Object[] arraies = list.toArray();
        Arrays.sort(arraies);
        final StringBuilder buffer = new StringBuilder();

        for(Object array: arraies) {
            buffer.append(array).append(param.get(array));
        }
        
        String sigString = buffer.toString();
        try {
            sigString = URLEncoder.encode(sigString,"utf-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
        return sigString + Constants.APP_SECKEY;
    }

    /**
     * Creates the sig string for login parameter.
     * 
     * @param inputString the string will be encoded with "SHA-1".
     * @return the encoded string with hex format.
     */
    private static String buildSigOutput(String in) {
        String out = "";
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            sha.update(in.getBytes());
            byte[]  sha1 = sha.digest();
            // 閺堬拷锟界紒鍫㈡晸閹存�HA缁涙儳鎮�byte2hex閺傝纭堕弰鐥搚te閺佹壆绮嶆潪锟斤拷鏉╂稑鍩楃�妤冾儊娑擄拷锟�
            out = byte2hex(sha1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }
    
    public static String getLoginSig(ArrayList<BasicNameValuePair> vpList) {
        return buildSigOutput(buildSigInput(vpList));
    }

    /**
     * convert the bytes to hex format.
     * 
     * @param b the contents in bytes format
     * @return the hex format string
     */
    private static String byte2hex(byte[] b) {
        final StringBuilder hs = new StringBuilder();
        String stmp = "";

        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }

        return hs.toString();
    }

    public static String getExtendSignature(HashMap<String,String> headerMap,String bodyMap)
    {
          String header ="ct/estore?" + HashMap2String(headerMap);

          String headerSig = buildSigOutput("21c410e7fa3542b3a0323c74637fc529"+bodyMap.length()+header);
          String bodySig = buildSigOutput("21c410e7fa3542b3a0323c74637fc529"+bodyMap);

        return headerSig+"|"+bodySig;   
    }
    
    private static String HashMap2String(HashMap<String,String> map)
    {
       
      final ArrayList<String> list = new ArrayList<String>();
      
      if (map==null)
          return "";
      
      for (HashMap.Entry<String, String> m : map.entrySet()) {
          list.add(m.getKey());
      }
      
      final Object[] arraies = list.toArray();
      final StringBuilder buffer = new StringBuilder();
      for(int i =0 ;i<arraies.length;i++) {
          if (i==arraies.length-1)
              buffer.append(arraies[i]).append("=").append(map.get(arraies[i]));
          else
              buffer.append(arraies[i]).append("=").append(map.get(arraies[i])).append("&");
      }
        
      return buffer.toString();
    }
    
    public static String getRegrards() {
        final int hour = Integer.parseInt(getHour());
        String regards = null;
        if((hour>=0 && hour<=6) || (hour>19 && hour<=24)) {
            regards = "閺呮矮绗傛總锟斤拷!";      
        } else if(hour>6 && hour<=9)  {
            regards = "閺冣晙绗傛總锟斤拷!";
        } else if(hour>9 && hour<=10) {
            regards = "娑撳﹤宕嶆總锟斤拷!";
        } else if(hour == 11) {
            int min = Integer.parseInt(getMin());
            if(min<=30) {
                regards = "娑撳﹤宕嶆總锟斤拷!";
            } else {
                regards = "娑擃厼宕嶆總锟斤拷!";
            }
        } else if(hour>=12 && hour<=14) {
            regards = "娑擃厼宕嶆總锟斤拷!";
        } else if(hour>14 && hour<=19) {
            regards = "娑撳宕嶆總锟斤拷!";
        }
        
        return regards;
    }
    
    private static String getHour() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String hour;
        hour = dateString.substring(11, 13);
        return hour;
    }
    
    /**
    * 瀵版鍩岄悳鏉挎躬閸掑棝鎸�
    *
    * @return
    */
    private static String getMin() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String dateString = formatter.format(currentTime);
        final String min = dateString.substring(14, 16);
        return min;
    }
    
    /**
     *閺冨爼妫块惃鍕壐瀵繗娴嗛崠鏍﹁礋yyyy-MM-dd hh:mm:ss.mss
     *
     * @param time the time
     * @return the string
     */
    public static String convertTime(String time){      
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.mss");
        Date date = new Date(Long.parseLong(time) * 1000);

        return  format.format(date);
    }
    
    public static String toZero(String name){
        if(name==null||"".equals(name)){
            return "0";
        }
        return name;
    }
    
    /** Base64 encode the given data */
    public static String encode(byte[] data) {
        int start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);
 
        int end = len - 3;
        int i = start;
        int n = 0;
 
        while (i <= end) {
            int d = ((((int) data[i]) & 0x0ff) << 16)
                    | ((((int) data[i + 1]) & 0x0ff) << 8)
                    | (((int) data[i + 2]) & 0x0ff);
 
            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);
 
            i += 3;
 
            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }
 
        if (i == start + len - 2) {
            int d = ((((int) data[i]) & 0x0ff) << 16)
                    | ((((int) data[i + 1]) & 255) << 8);
 
            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            int d = (((int) data[i]) & 0x0ff) << 16;
 
            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }
 
        return buf.toString();
    }
    
    private static final char[] legalChars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        .toCharArray();
}
